package com.example.dqdq.lzyim_asm_tvapp.utils;

import org.json.JSONException;
import org.json.JSONObject;

import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;

import org.xutils.common.Callback;
import org.xutils.x;

import com.example.dqdq.lzyim_asm_tvapp.api.API;
import com.example.dqdq.lzyim_asm_tvapp.https.HttpManger;

/*
 * APP 自动更新
 * 流程：
 * 先从服务器取回最新版本，如果服务器版本大于当前app版本，则再次发送请求获得APK下载地址，最后进行安装
 */
public class CheckAppUpdate {

	public static void doCheck(final Context context) {
		final int app_version = getAppInfo(context).versionCode; // 当前APP版本

//		final String serUrl = ServerUrlUtils.getServerUrl(context) + "app/v1/getAppVersion.html";

		x.http().post(HttpManger.getParams(API.USER_DATA_SELECT,"random",""), new Callback.CommonCallback<String>() {
			@Override
			public void onSuccess(String result) {
				try {
					// 最新安装包地址
					String apkUrl = API.SERVERC_URL+ "cms_t.apk";

					JSONObject jsonobject = new JSONObject(result);
					String status = jsonobject.getString("status");
					if (status.equals("SUCCESS")) {
						int server_app_version = Integer.parseInt(jsonobject.getString("info"));
						if (app_version < server_app_version) {
							System.err.println("更新App");
//							UpdateManager up = new UpdateManager(context);
//							up.checkUpdateInfo(apkUrl);
						}
						System.err.println("不更新App");
					} else {
//						Toast.makeText(context, jsonobject.getString("info"), Toast.LENGTH_LONG).show();
						System.err.println("App版本，网络请求失败！Error:" + jsonobject.getString("info"));
					}
				} catch (JSONException ex) {
					ex.printStackTrace();
				}
			}

			@Override
			public void onError(Throwable ex, boolean isOnCallback) {

			}

			@Override
			public void onCancelled(CancelledException cex) {

			}

			@Override
			public void onFinished() {

			}
		});
	}

	// 获取APP信息
	public static PackageInfo getAppInfo(Context context) {
		PackageManager packageManager = context.getPackageManager();
		PackageInfo packageInfo = null;
		try {
			packageInfo = packageManager.getPackageInfo(context.getPackageName(), 0);
		} catch (NameNotFoundException e) {
			e.printStackTrace();
		}
		return packageInfo;
	}
}
